/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 /***************************************************************************
 * Name: lz4_encoder.c
 *
 * Purpose: implementation a encoder with zstd compress
 *
 * Developer:
 *   wen.gu , 2022-03-04
 *
 * TODO:
 *
 ***************************************************************************/

 /******************************************************************************
 **    INCLUDES
 ******************************************************************************/

#include "zstd_encoder.h"

#include <stdio.h>
#include <string.h>
/******************************************************************************
 **    MACROS
 ******************************************************************************/
#define LOGE printf
#define LOGD printf
/******************************************************************************
 **    VARIABLE DEFINITIONS
 ******************************************************************************/

/******************************************************************************
 **    inner FUNCTION DEFINITIONS
 ******************************************************************************/

/******************************************************************************
 **    FUNCTION DEFINITIONS
 ******************************************************************************/

ZstdEncoder::ZstdEncoder()
{
    zstd_stream_ = ZSTD_createCStream();

   size_t err = ZSTD_CCtx_setParameter(zstd_stream_, ZSTD_c_compressionLevel, ZSTD_maxCLevel());
    if (ZSTD_isError(err))
    {
        LOGE("sztd set compression level failed(%s)\n", ZSTD_getErrorName(err));
    }
#if 0
    err = ZSTD_CCtx_setParameter(zstd_stream_, ZSTD_c_strategy, ZSTD_btultra2);
    if (ZSTD_isError(err))
    {
        LOGE("sztd set compression level failed(%s)\n", ZSTD_getErrorName(err));
    }
#endif

}

ZstdEncoder::~ZstdEncoder()
{
    if (zstd_stream_)
    {
        ZSTD_freeCStream(zstd_stream_);
    }
}

bool ZstdEncoder::encode(const uint8_t* src, uint32_t src_size, KfaBuffer& out_buf)
{
    /* Set the input buffer to what we just read.
        * We compress until the input buffer is empty, each time flushing the
        * output.
        */
    ZSTD_inBuffer input = { src, src_size, 0 }; 

    uint32_t dst_size = ZSTD_compressBound(src_size);
    uint8_t* dst_buf = new uint8_t[dst_size];
    uint32_t dst_pos = 0;
    int finished;

    do {
        /* Compress into the output buffer and write all of the output to
            * the file so we can reuse the buffer next iteration.
            */
        ZSTD_outBuffer output = { dst_buf + dst_pos, dst_size - dst_pos, 0 };
        size_t const remaining = ZSTD_compressStream2(zstd_stream_, &output , &input, ZSTD_e_continue);

        if (ZSTD_isError(remaining))
        {
            LOGE("sztd compress failed(%s)\n", ZSTD_getErrorName(remaining));
            return false;
        }
        LOGD("[%s.%d]===>: in pos: %d, size: %d, out size: %d\n", __FUNCTION__, __LINE__, input.pos, input.size, output.pos);
        dst_pos += output.pos;

        /* If we're on the last chunk we're finished when zstd returns 0,
            * which means its consumed all the input AND finished the frame.
            * Otherwise, we're finished when we've consumed all the input.
            */
        finished = (input.pos == input.size);
    } while (!finished);

    out_buf.buf = dst_buf;
    out_buf.size = dst_pos;
    out_buf.release = [](KfaBuffer& buf)
    {
        if (buf.buf)
        {
            delete[] buf.buf;
        }        
    };

    return true;
}